# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def balanceBST(self, root: TreeNode) -> TreeNode:
        def inorder(node, array):
            if node.left:
                inorder(node.left, array)
            array.append(node.val)
            if node.right:
                inorder(node.right, array)

        def construct(array, left, right):
            if right < left:
                return None
            if right - left == 0:
                return TreeNode(array[left])
            mid = (left + right) // 2
            node = TreeNode(array[mid])
            node.left = construct(array, left, mid - 1)
            node.right = construct(array, mid + 1, right)

            return node

        array = []
        inorder(root, array)

        return construct(array, 0, len(array) - 1)
